package edu.ccut.saturn.basevalidate.businessvalidate;

import edu.ccut.saturn.component.DefaultSaturnValidate;
import edu.ccut.saturn.component.ValidateResult;

public class CompareValidate extends DefaultSaturnValidate {
	/**
	 * 目前开放数值比较
	 */
	private static final String EQUALS = "==";// == //$NON-NLS-1$
	private static final String NON_EQUALS = "!=";// != //$NON-NLS-1$
	private static final String LESS_THEN = "<";// < //$NON-NLS-1$
	private static final String MORE_THEN = ">";// > //$NON-NLS-1$
	private static final String MORE_THEN_EQUALS = ">=";// > //$NON-NLS-1$
	private static final String LESS_THEN_EQUALS = "<=";// > //$NON-NLS-1$
	
	private static final String accountRegExpr = "^-?(\\d*)([.]{0,1})(\\d{1,})$";

	public void doValidate(Object value, Object[] args, ValidateResult result) {
		double origin = 0;
		boolean hasError = false;
		
		//输入值是数值以外的值时返回的错误信息
		if(!(value.toString()).matches(accountRegExpr)){
			sendError("_valueError_", value, result);
			return;
		}
		//参数值不正确时返回的错误信息
		if (args == null || args.length % 2 != 0) {
			sendError(_ARGERROR_, value, result);
			return;
		}
		
		origin = Double.parseDouble(value + "");
			
		for (int i = 0; i < args.length; i++) {
			String exp = ((String) args[i]).trim();
			double param = Double.parseDouble((String) args[++i]);

			if (EQUALS.equals(exp)) {
				if (origin != param) {
					hasError = true;
					break;
				}
				continue;
			}

			if (LESS_THEN.equals(exp)) {
				if (origin >= param) {
					hasError = true;
					break;
				}
				continue;
			}

			if (MORE_THEN.equals(exp)) {
				if (origin <= param) {
					hasError = true;
					break;
				}
				continue;
			}

			if (NON_EQUALS.equals(exp)) {
				if (origin == param) {
					hasError = true;
					break;
				}
				continue;
			}

			if (MORE_THEN_EQUALS.equals(exp)) {
				if (origin < param) {
					hasError = true;
					break;
				}
				continue;
			}

			if (LESS_THEN_EQUALS.equals(exp)) {
				if (origin > param) {
					hasError = true;
					break;
				}
				continue;
			}
			
            //表达式不正确时返回的错误信息
			sendError("_expError_", value, result);
			return;
		}
		
		//校验值不正确时返回的错误信息
		if (hasError) {
			sendError(_ERROR_, value, result);
		}
	}	
}
